package com.lalosoft.misgastos.view;

import java.util.List;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.lalosoft.misgastos.domain.Item;
import com.lalosoft.misgastos.listener.DeleteItemListener;

public class ItemListView extends ListView {
	
	private DeleteItemListener listener;

	public ItemListView(Context context) {
		super(context);
		init(context);
	}
	
	public ItemListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}
	
	public ItemListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	private void init(Context context) {		
		ItemsAdapter itemsAdapter = new ItemsAdapter();
		setAdapter(itemsAdapter);
	}
	
	public void setActionItemListener(DeleteItemListener listener){
		this.listener = listener;
	}
	
	public void setItemList(List<Item> list){
		ItemsAdapter itemsAdapter = (ItemsAdapter)getAdapter();
		itemsAdapter.setIconList(list);
	}
	
	private class ItemsAdapter extends BaseAdapter{
		private List<Item> list;
		
		@Override
		public int getCount() {
			if(list != null){
				return list.size();
			}
			return 0;
		}
		
		public void setIconList(List<Item> list){
			this.list = list;
			notifyDataSetChanged();
		}

		@Override
		public Object getItem(int position) {
			if(list != null && position >= 0 && position < list.size()){
				return list.get(position);
			}
			
			return 0;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Object obj = getItem(position);
			ItemListItemView v = null;
			if(obj != null && obj instanceof Item){
				Item item = (Item)obj;
				
				if(convertView instanceof ItemListItemView){
					v = (ItemListItemView)convertView;
				}else{
					v =  new ItemListItemView(getContext());
				}
				v.setActionItemListener(listener);
				v.setItem(item);
			}
			return v;
		}
	}
	
}
